"""
常用工具
"""
import time

from selenium.common import NoSuchElementException
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import logging.config
from conf import settings

logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
logger = logging.getLogger("搜索主机")  # 生成一个系统版本获取log实例


def wait_table(browser):
    """
    主机、从账号等待加载
    :param browser:
    :return:
    """
    for i in range(1000):  # 1000 等待100秒
        time.sleep(0.1)  # 轮询评论 0.1秒
        if not browser.find_element(By.XPATH, '//*[@id="load_list"]').is_displayed():
            break


def wait_list(browser):
    """
    授权等待加载
    :param browser:
    :return:
    """
    for i in range(1000):  # 1000 等待100秒
        time.sleep(0.1)  # 轮询评论 0.1秒
        if not browser.find_element(By.XPATH, '//*[@id="load_selectedEntityList"]').is_displayed():
            if not browser.find_element(By.XPATH, '//*[@id="load_unselectedEntityList"]').is_displayed():
                break


def return_page(browser, wait):
    """
    返回设备管理页面
    :param browser:
    :param wait:
    :return:
    """
    browser.switch_to.parent_frame()
    # 设备管理
    wait.until(EC.element_to_be_clickable((
        By.XPATH, '//*[@id="IndexMenuUL"]/li[3]/table/tbody/tr/td[2]'
    ))).click()
    # 子iframe切换
    browser.switch_to.frame('LT_main')
    # 等待加载
    wait_table(browser)


def host_row_search(browser, host):
    """
    主机搜索
    :return:
    """
    # 输入IP查询
    input_ip_element = browser.find_element(By.XPATH, '//*[@id="defaultIp"]')
    for i in input_ip_element.get_attribute("value"):
        input_ip_element.send_keys(Keys.BACKSPACE)
    browser.find_element(By.XPATH, '//*[@id="defaultIp"]').send_keys(host.ip)
    search = browser.find_element(
        By.XPATH,
        '/html/body/div[1]/div/div[1]/div[4]/div/table/tbody/tr[3]/td[7]/div/table/tbody/tr/td[2]/input'
    )
    search.click()
    # browser.execute_script("arguments[0].click();", search)
    # 等待加载
    wait_table(browser)
    # 分析主机信息
    text_list = []
    try:
        for i in range(1, 150):
            text_list.clear()
            host_row = browser.find_element(By.XPATH, f'//*[@id="{i}"]')
            for text in host_row.text.split(" "):
                text_list.append(text)
            if text_list[2] == host.ip and text_list[1] == '主机':
                print("查询到该主机")
                host.os_release = text_list[4]  # 记录系统版本
                host.sync_status = text_list[7]  # 记录同步状态
                logger.info(f"主机 {host.ip} 系统版本为 {host.os_release}  同步状态为 {host.sync_status}")
                if host.sync_status not in ["正常", "同步失败"]:  # 判断同步状态 是否为问题主机
                    host.is_bad = True
                # 保存到excel并返回当前主机行
                host.save()
                return host_row
    except NoSuchElementException as e:
        if i == 16:
            host.os_release = "此页可能没有该主机NoSuchElement"
            logger.warning(f"主机 {host.ip} : 此页可能没有该主机NoSuchElement")
            host.is_bad = True
            print("查询结束，此页可能没有该主机")
        else:
            host.os_release = "没有此主机NoSuchElement"
            host.is_bad = True
            logger.error(f"主机 {host.ip} : 没有此主机NoSuchElement")
            print("没有该主机")
    host.save()
    return None
